package com.ruoyi.system.controller;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取用户列表
     */
    @GetMapping("/pageList")
    @ApiOperation(value = "获取用户列表(分页)", response = SysUser.class)
    public TableDataInfo pageList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取用户列表", response = SysUser.class)
    public AjaxResult list(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        return success(list);
    }

    /**
     * 获取用户列表
     */
    @InnerAuth
    @PostMapping("/userlist")
    @ApiOperation(value = "获取用户列表（内部请求）", response = SysUser.class)
    public R<List<SysUser>> userlist(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        return R.ok(list);
    }

    /**
     * 获取用户角色列表
     */
    @InnerAuth
    @PostMapping("/userRoleList")
    @ApiOperation(value = "获取用户列表（内部请求）", response = SysUser.class)
    public R<List<SysUser>> userRoleList(SysUser user) {
        List<SysUser> list = userService.selectUserRoleList(user);
        return R.ok(list);
    }

    /**
     * 获取用户树状列表
     */
    @GetMapping("/treelist")
    @ApiOperation(value = "获取用户树状列表", response = SysUser.class)
    public AjaxResult treelist(SysUser user) {
        user.setOrgId(SecurityUtils.getLoginUser().getSysUser().getOrgId());
        List<SysUser> list = userService.selectTreeUser(user);
        return success(list);
    }

    @Log(title = "导出用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出用户")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "导入用户", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ApiOperation(value = "导入用户")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @Log(title = "导入用户模板", businessType = BusinessType.IMPORT)
    @PostMapping("/importTemplate")
    @ApiOperation(value = "导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}/{orgId}/{orgName}")
    @ApiOperation(value = "获取当前用户信息(内部请求)")
    public R<LoginUser> info(@ApiParam(value = "用户名称", required = true) @PathVariable("username") String username, @ApiParam(value = "机构", required = true) @PathVariable("orgId") Long orgId, @PathVariable("orgName") String orgName) {
        SysUser sysUser = userService.selectLoginUserByUserName(username, orgId, orgName);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        Integer[] groupIds = userService.selectUserGroupIds(sysUser.getUserId());
        // 角色集合
        Object[] roleObject = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles((Set<String>) roleObject[0]);
        sysUserVo.setRoleIds((Long[]) roleObject[1]);
        sysUserVo.setPermissions(permissions);
        if (groupIds != null) {
            sysUserVo.setGroupIds(groupIds);
        }
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}/{orgId}")
    @ApiOperation(value = "获取当前用户信息(内部请求)")
    public R<LoginUser> info(@ApiParam(value = "用户名称", required = true) @PathVariable("username") String username, @ApiParam(value = "机构", required = true) @PathVariable("orgId") Long orgId) {
        SysUser sysUser = userService.selectLoginUserByUserName(username, orgId, null);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        Integer[] groupIds = userService.selectUserGroupIds(sysUser.getUserId());
        // 角色集合
        Object[] roleObject = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles((Set<String>) roleObject[0]);
        sysUserVo.setRoleIds((Long[]) roleObject[1]);
        sysUserVo.setPermissions(permissions);
        if (groupIds != null) {
            sysUserVo.setGroupIds(groupIds);
        }
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    @ApiOperation(value = "注册用户信息")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation(value = "获取用户信息")
    public AjaxResult getInfo() {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合

        Object[] roleObject = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", (Set<String>) roleObject[0]);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation(value = "根据用户编号获取详细信息")
    public AjaxResult getInfo(@ApiParam(value = "用户id", required = false) @PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId, null);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/{userId}/{orgId}"})
    @ApiOperation(value = "根据用户编号获取详细信息")
    @InnerAuth
    public AjaxResult getInfoWithoOrgId(@PathVariable("userId") Long userId, @PathVariable Long orgId) {
        userService.checkUserDataScope(userId, orgId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    @InnerAuth
    @GetMapping("/remote/{userId}")
    @ApiOperation(value = "根据用户编号获取详细信息(远程接口)")
    public R<SysUser> remoteGetInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId, null);
        SysUser sysUser = userService.selectUserById(userId);
        return R.ok(sysUser);
    }

    /**
     * 新增用户
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增用户")
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        String loginUserIsMobile = CacheConstants.SYS_CONFIG_KEY + "loginUserIsMobile";
        Boolean isValidate = Convert.toBool(redisService.getCacheObject(loginUserIsMobile));
        if (isValidate != null && isValidate) {
            if (UserConstants.NOT_UNIQUE.equals(userService.checkUserName(user))) {
                return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            }
            Boolean validPhoneNumber = userService.isValidPhoneNumber(user.getUserName());
            if (!validPhoneNumber) {
                return error("新增用户'" + user.getUserName() + "'失败，登录账号不符合手机号的规则");
            }
        } else {
            if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
                return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                    && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
                return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            } else if (StringUtils.isNotEmpty(user.getEmail())
                    && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
                return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }
        }

        user.setOrgId(SecurityUtils.getLoginUser().getSysUser().getOrgId());
        user.setCreateBy(SecurityUtils.getUsername());
        // user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改用户")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId(), null);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{userIds}")
    @ApiOperation(value = "删除用户")
    public AjaxResult remove(@ApiParam(value = "用户id", required = true) @PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    @ApiOperation(value = "重置密码")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId(), null);
        //获取默认密码
        String password = configService.selectConfigByKey("sys.user.initPassword");
        if (StringUtils.isNull(password)) return error("获取默认密码失败");
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setUpdateBy(SecurityUtils.getUsername());
        userService.resetPwd(user);
        return toAjax(password);
    }

    /**
     * 状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation(value = "状态修改")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId(), null);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    @ApiOperation(value = "根据用户编号获取授权角色")
    public AjaxResult authRole(@ApiParam(value = "用户id", required = true) @PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    @ApiOperation(value = "用户授权角色")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId, null);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    @ApiOperation(value = "获取部门树列表")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 随机获取当前登录用户的个人签名
     */
    @InnerAuth
    @GetMapping("/getMySign")
    @ApiOperation(value = "随机获取当前登录用户的个人签名")
    public R<String> getMySign() {
        String signImage = userService.getRandomMySign(null);
        if (signImage == null) return R.fail("未找到签名图片！");
        return R.ok(signImage);
    }

    /**
     * 随机获取指定用户的个人签名
     */
    @InnerAuth
    @GetMapping("/getMySign/{userId}")
    @ApiOperation(value = "随机获取指定用户的个人签名")
    public R<String> getMySignByUserId(@PathVariable("userId") Long userId) {
        String signImage = userService.getRandomMySign(userId);
        if (signImage == null) return R.fail("未找到签名图片！");
        return R.ok(signImage);
    }

    /**
     * 随机获取当前登录用户的个人签名
     */
    @GetMapping("/local/getMySign")
    @ApiOperation(value = "随机获取当前登录用户的个人签名")
    public R<String> localGetMySign() {
        String signImage = "data:image/gif;base64," + userService.getRandomMySign(null);
        if (signImage == null) return R.fail("未找到签名图片！");
        return R.ok(signImage);
    }

}
